package com.hqyj.javaSpringBoot.filter;



import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Description ParamFilter, 删除请求中的 "fuck" 字符串
 * @Author
 * @Date
 */
@WebFilter(filterName="paramFilter", value={"/*"})//注册bean
public class ParamFilter implements Filter {

    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("==== Do Filter ====");
        HttpServletRequest re = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(re) {
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);//获取查询参数的value值
                if (StringUtils.isNotBlank(value)) {//判断value不为空
                    value = value.replaceAll("fuck", "***");
                }
                return value;
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                // stream api： 数组 ---- list ---- 处理数据 ---- 转化为数组
                //Arrays.asList(values)将values转换为list，
                //stream()转换为流对象
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck", "***"))//对每一项进行处理，遍历后调用replaceAll方法替换字符
                        .toArray(String[] :: new);//转换为string数组  new为方法名 前面为类名
            }
        };

        chain.doFilter(wrapper, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==== Init Filter ====");
    }

    @Override
    public void destroy() {
        LOGGER.debug("==== destroy Filter ====");
    }
}
